<template>
  <div class="oe-current-exam" v-loading="loading">
    <info-top @toggleCollapsed="toggleCollapsed" :examShow="false"></info-top>
    <div class="oe-exam-content">
      <div class="oe-exam-top">
        {{ title }}
        <span style="color:red;float:right" v-if="monitorMobile">技术人员电话：{{ monitorMobile }}</span>
      </div>
      <div class="clearfix">
        <!-- <div>抓拍次数{{captureNum}}</div>
        <div>动态的时间{{currentExamTime}}</div>
        <div style="width: 1100px; display: inline-block; word-break: break-all;">
          <div style="display: inline-block;width: 100px;margin: 0px 5px;" v-for="(item, index) in captureNumList" :key="index">
            <span style="display: inline-block;with: 26px;text-align: right;">{{index+1}}:</span>
            <span style="color: #f00;">({{item}})</span>
          </div>
        </div> -->
        <div style="margin-top: 20px;transform: translateY(0);">
          <div
          id="home-tab"
          class="answer-sheet fl"
          :class="{ 'fixed-style': scrollTop - 20 > tabOffsetTop }"
        >
          <div class="oe-exam-frame">
            <div class="oe-exam-container" style="height: 240px;" v-show="isUseCamera">
              <video id="video" width="280" height="240" preload autoplay loop muted></video>
              <canvas id="canvas" width="280" height="240"></canvas>
              <canvas id="canvas2" width="320" height="240" style="display:none;"></canvas>
            </div>
          </div>
          <div class="answer-sheet-top answer-sheet-topLine">答题卡</div>
          <div style="font-size：20px;color: #f00;margin-top:5px;">
            倒计时：{{ LimitTime | countdown }}
            <span
              v-if="showDelayedTime > 0"
            >(+{{ showDelayedTime }}分钟)</span>
          </div>
          <div>
            <div class="quetion-type-list" style="margin-top: 15px;">
              <a
                class="que-type-lis"
                v-for="(item, index) in answerSheetList"
                :key="index"
                :class="{ queActivate: item.Answer }"
                :href="'#' + item.QuestionId"
              >{{ item.num }}</a>
            </div>
          </div>
          <div class="answer-bottom clearfix">
            <div class="fr">
              <span class="answer-dian" style="background:#0177D5;"></span>已答
            </div>
            <div class="fr">
              <span class="answer-dian"></span>未答
            </div>
          </div>
          <a-button type="primary" class="fr" style="margin-top:10px;" @click="showConfirm">提交试卷</a-button>
        </div>
        </div>
        
        <div class="oe-quetion-list fr" v-if="quesTimeShow">
          <div v-if="tiType != 'answer'" style="color: #f00;text-align:center;font-size:20px;line-height:24px;margin-top:10px;"
          >时间未到不能作答(距离开始还有{{ needSeconds | countdown }})</div>
          <testPaper ref="testPaper" v-if="questionShow" :uploadType="uploadType" :allAnswerList="allAnswerList" :questionData="questionData" :mode="tiType != 'answer'?'check':''" :onlyWatch="tiType"></testPaper>
          <a-button type="primary" class="fr" style="margin-right:20px;" @click="showConfirm">提交试卷</a-button>
        </div>
      </div>
    </div>
    <a-modal
      v-model="visible"
      title="提示信息"
      onOk="handleOk"
      :closable="false"
      :keyboard="false"
      :maskClosable="false"
      width="800px"
      v-if="nowChangeCount != chageCount"
    >
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
      <div style="text-align: center;">
        <p style="font-size: 18px;color:#F56C6C;">请不要离开考试界面，认真答题！您离开页面的信息已记录</p>
        <p style="font-size: 18px;color:#F56C6C;">
          请注意：您已离开页面{{ nowChangeCount }}次
          <span
            v-if="chageCount != -2 && isShowPaperCount"
          >，再离开{{ otherCount }}次，系统将自动提交您的作答记录</span>
        </p>
      </div>
    </a-modal>
    <a-modal
      class="oe-exam-showWarningModal"
      v-model="showWarningModal"
      title="系统提示"
      onOk
      :closable="false"
      :keyboard="false"
      :maskClosable="false"
    >
      <template slot="footer">
        <a-button @click="closeWarningModal">确定</a-button>
      </template>
      <div style="text-align: center;">
        <p style="font-size: 16px;color:#F56C6C;">
          警告！系统检测到您于{{ warningTime }}人脸显示异常，请调整好答题姿势，监测到{{ stuCatCount1 }}次
          <span
            v-if="cameraChangeCount != -2 && isShowCameraCount"
          >，剩余{{ otherCount1 }}次，否则系统判定违规，将自动交卷！</span>
        </p>
      </div>
    </a-modal>
  </div>
</template>

<script>
// 对HTML标签进行过滤, 防止XSS攻击
import xss, { whiteList } from 'xss';
import infoTop from '@/components/info-top/index.vue';
import testPaper from '@/components/testPaper/index.vue';

import '@/lib/faceTrack/tracking-min.js';
import '@/lib/faceTrack/eye-min.js';
// xss 选项
const xss_options = {};

export default {
  components: {
    infoTop,
    testPaper
  },
  props: {
    Id: {
      type: String,
      default: ''
    },
    routerGo: {
      type: Boolean,
      default: false
    },
    paperType: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      title: '',
      monitorMobile: '',
      list: [],
      tiType: 'answer',
      answerSheetList: [],
      queList: [],
      loading: true,
      show: false,
      workExamStuId: '',
      visible: false,
      IsProhibitCopy: false,
      stuCatCount: 0,
      otherCount: 0,
      nowChangeCount: 0,
      useTime: 0,
      useTimeInterval: '',
      LimitTime: 0,
      tabOffsetTop: 0,
      scrollTop: 0,
      chageCount: 0,
      isShowQuesType: false,
      isShowBaseScore: false,
      examPicCaptrue: '',
      trackerTask: '',
      mediaStreamTrack: '',
      showWarningModal: false,
      warningTime: '',
      needSeconds: 0,
      cameraChangeCount: 0,
      stuCatCount1: 1,
      otherCount1: 0,
      currentExamTime: 0,
      randomCameraFlag: false,
      isLeave: false,
      isUseCamera: true,
      isShowCameraCount: true,
      isShowPaperCount: true,
      minSubmitTime: 0,
      isStart: true,
      showDelayedTime: 0,
      isRandomPhoto: false,
      uploadType: 0,
      questionShow: false,
      questionData: '',
      allAnswerList: [],
      quesTimeShow: true,
      saving:false,
      schoolId: localStorage.getItem('schoolId'),
      checkFaceTime: 0,
      photoCount: 0,
      captureNum: 0,
      captureNumList: []
    };
  },
  filters: {
    countdown(e) {
      var time = e;
      if (null != time && '' != time) {
        if (time > 60 && time < 60 * 60) {
          time =
            parseInt(time / 60.0) + '分钟' + parseInt((parseFloat(time / 60.0) - parseInt(time / 60.0)) * 60) + '秒';
        } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
          time =
            parseInt(time / 3600.0) +
            '小时' +
            parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) +
            '分钟' +
            parseInt(
              (parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) -
                parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) *
                60
            ) +
            '秒';
        } else if (time >= 60 * 60 * 24) {
          time =
            parseInt(time / 3600.0 / 24) +
            '天' +
            parseInt((parseFloat(time / 3600.0 / 24) - parseInt(time / 3600.0 / 24)) * 24) +
            '小时' +
            parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) +
            '分钟' +
            parseInt(
              (parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) -
                parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) *
                60
            ) +
            '秒';
        } else {
          time = parseInt(time) + '秒';
        }
      }
      return time;
    }
  },
  watch: {
    visible(e) {
      if (e) {
        this.saveCutPage();
      }
    }
  },
  destroyed() {
    localStorage.setItem('useTime' + this.workExamStuId, this.useTime);
    clearInterval(this.useTimeInterval);
    clearInterval(this.examPicCaptrue);
    clearInterval(this.cameraRandomCapTimer);
    window.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('blur', this.getBlur);
    // 停止侦测
    // if (this.isUseCamera) {
    //   this.trackerTask.stop();
    // }
    // 关闭摄像头
    // this.trackerTask.closeCamera();
    // window.tracking.closeCamera();
    if (this.isUseCamera) {
      this.mediaStreamTrack.srcObject && this.mediaStreamTrack.srcObject.getTracks()[0].stop();
    }
    window.removebeforeunload = function(e) {
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '关闭提示';
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '关闭提示';
    };

    // 解除右键菜单
    document.oncontextmenu = function() {
      return true;
    };
    // 解除文字选择
    document.onselectstart = function() {
      return true;
    };
    // 解除复制
    document.oncopy = function() {
      return true;
    };
    // 解除剪切
    document.oncut = function() {
      return true;
    };
    // 解除粘贴
    document.onpaste = function() {
      return true;
    };
  },
  created() {
    this.$nextTick(() => {
      window.addEventListener('blur', this.getBlur);
      window.onbeforeunload = function(e) {
        e = e || window.event;
        // 兼容IE8和Firefox 4之前的版本
        if (e) {
          e.returnValue = '关闭提示';
        }
        // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
        return '关闭提示';
      };

      let tabEle = document.getElementById('home-tab');
      this.tabOffsetTop = tabEle.offsetTop;
      window.addEventListener('scroll', this.handleScroll);
    });
  },
  mounted() {
    if (!this.routerGo) {
      this.$router.go(-1);
    }
    this.examPreview();
    setTimeout(() => {
      this.getEnabled();
    }, 1000);
  },
  methods: {
    // 考试录像
    openCamera() {
      var video = (this.mediaStreamTrack = document.getElementById('video'));
      var canvas = document.getElementById('canvas');
      var canvas2 = document.getElementById('canvas2');
      window.navigator.mediaDevices
        .getUserMedia({
          video: true,
          audio: false
        })
        .then(function(stream) {
          video.srcObject = stream;
          tracking.track('#video', tracker);
          this.isStart = true;
        })
        .catch(function(err) {});
      var context = canvas.getContext('2d');
      var tracker = new window.tracking.ObjectTracker('eye');
      tracker.setInitialScale(1);
      tracker.setStepSize(1);
      tracker.setEdgesDensity(0.1);

      var _this = this;
      tracker.on('track', function(event) {
        console.log(event.data.length > 0);
        if (_this.isStart) {
          var cameraInterval = setInterval(function() {
            if (_this.isLeave) {
              console.log('离开考试区域');
              _this.warningTime = _this.$moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
              _this.snap();
            } else {
              console.log('在考试区域');
            }
            _this.isLeave = true;
          }, 8000);
          this.isStart = false;
        }
        if (event.data.length > 0) {
          _this.isLeave = false;
        }
      });
      if (_this.isStart) {
        // if (this.schoolId == '5dqqakqn-6fotqedz8b22q' || this.schoolId == 'fwonav2ni7zexp7iavcvqq') {
        //   this.examPicCaptrue = setInterval(function() {
        //     if (_this.isLeave && _this.cameraChangeCount != -1) {
        //       console.log('离开考试区域1');
        //       _this.warningTime = _this.$moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
        //       _this.showWarningModal = true;
        //       _this.snap();
        //     } else {
        //       console.log('在考试区域1');
        //     }
        //     _this.isLeave = true;
        //   }, 10000);
        // } else {
          this.examPicCaptrue = setInterval(function() {
            if (_this.isLeave && _this.cameraChangeCount != -1) {
              console.log('离开考试区域1');
              _this.warningTime = _this.$moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
              _this.snap();
            } else {
              console.log('在考试区域1');
            }
            _this.isLeave = true;
          }, this.checkFaceTime*1000);
        // }
        this.isStart = false;
      }
    },
    snap() {
      var video = (this.mediaStreamTrack = document.getElementById('video'));
      var canvas2 = document.getElementById('canvas2');
      //绘制canvas图形
      canvas2.getContext('2d').drawImage(video, 0, 0, 320, 240);
      //执行上传
      this.saveExamPic(canvas2);
    },
    snapst() {
      if(!this.isUseCamera){
        return
      }
      console.log('执行抓拍了');
      var video = (this.mediaStreamTrack = document.getElementById('video'));
      var canvas2 = document.getElementById('canvas2');
      //绘制canvas图形
      canvas2.getContext('2d').drawImage(video, 0, 0, 320, 240);
      //执行上传
      let completeUrl = canvas2.toDataURL('image/png');
      let urlArr = completeUrl.split(',');
      let base64 = urlArr[1];
      let imgType = urlArr[0].replace('data:image/', '').replace(';base64', '');
      let file_system_url = localStorage.getItem('file_system_url');
      let postUrl = `${file_system_url}&extension=${imgType}&encode=base64`;
      this.$http.post(postUrl, base64).then((data) => {
        this.randomSaveCameraPage(data.url);
        this.randomCameraFlag = false;
      });
    },
    saveExamPic(canvas2) {
      if (this.isLeave) {
        let completeUrl = canvas2.toDataURL('image/png');
        let urlArr = completeUrl.split(',');
        let base64 = urlArr[1];
        let imgType = urlArr[0].replace('data:image/', '').replace(';base64', '');
        let file_system_url = localStorage.getItem('file_system_url');
        let postUrl = `${file_system_url}&extension=${imgType}&encode=base64`;
        this.$http.post(postUrl, base64).then((data) => {
          if (data) {
            if (this.randomCameraFlag) {
              this.randomSaveCameraPage(data.url);
              this.randomCameraFlag = false;
            } else {
              console.log('违规拍照');
              this.saveCameraCutPage(data.url);
            }
          }
        });
      }
    },
    saveCameraCutPage(url) {
      var browser = this.getBrowser();
      this.$http
        .post('/api/study/workexam/saveCameraCutPage', {
          workExamStuId: this.workExamStuId, //学生作答Id
          workExamId: this.Id, //考试Id
          browser: browser, //浏览器类型
          url: url
        })
        .then((res) => {
          if (res.code > 0) {
            this.stuCatCount1 = res.stuCatCount;
            this.showWarningModal = true;
            if (this.cameraChangeCount != -2) {
              this.otherCount1 = res.otherCount;
              if (res.stuCatCount >= this.cameraChangeCount) {
                this.mediaStreamTrack.srcObject.getTracks()[0].stop();
                this.$message.loading({ content: '摄像监测次数已达到最大次数！试卷自动提交中' });
                this.randomCameraFlag = true;
                this.loading = true
                this.snapst();
                setTimeout(() => {
                  this.onlineExamSave();
                }, 2000);
              }
            }
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    randomSaveCameraPage(url) {
      var browser = this.getBrowser();
      this.$http
        .post('/api/study/workexam/randomSaveCameraPage', {
          workExamStuId: this.workExamStuId, //学生作答Id
          workExamId: this.Id, //考试Id
          browser: browser, //浏览器类型
          url: url
        })
        .then((res) => {
          this.captureNum++
        });
    },
    closeWarningModal() {
      this.showWarningModal = false;
    },
    examPreview() {
      this.loading = true;
      this.$http
        .post('/api/study/workexam/examPreview', {
          examId: this.Id, //考试Id
          sourceType: 1
        })
        .then((res) => {
          if (res.code > 0) {
            this.loading = false;
            this.title = res.title;
            this.monitorMobile = res.monitorMobile;
            this.list = res.list;
            this.setAllQuestionAnswer(res.list);
            this.uniqueId = res.structId;
            // 时间记录
            this.LimitTime = res.LimitTime;
            this.minSubmitTime = res.minSubmitTime; //最小提交时长
            this.workExamStuId = res.workExamStuId;
            this.chageCount = res.chageCount; //最大切屏次数,
            this.IsProhibitCopy = res.IsProhibitCopy; //是否禁止复制,
            this.setIsProhibitCopy();
            this.nowChangeCount = res.nowChangeCount; //现在已切屏次数,
            this.otherCount = res.chageCount - res.nowChangeCount; //剩余切屏次数,
            this.cameraChangeCount = res.cameraChangeCount; //摄像监测次数
            this.isShowQuesType = res.isShowQuesType; //是否展示题型
            this.isShowBaseScore = res.isShowScore; //是否展示分数
            this.needSeconds = parseInt(res.needSeconds); //还需要多少秒可以作笞
            this.needSeconds = res.needSeconds; //还需要多少秒可以作笞
            this.isUseCamera = res.isUseCamera;
            this.isShowCameraCount = res.isShowCameraCount;
            this.isShowPaperCount = res.isShowPaperCount;
            this.uploadType = res.uploadType;
            if (res.isRepair) {
              this.paperType = 1;
            } else {
              this.paperType = 0;
            }
            this.setUseTime();
            this.isRandomPhoto = res.isRandomPhoto;
            this.checkFaceTime = res.checkFaceTime; //人脸检测时间
            this.photoCount = res.photoCount; //随机抓拍数量
            let cameraRandomCapTime = [];
            if (res.isRandomPhoto) {
              var intervalOne = Math.floor(this.photoCount/2);
              var one = Math.floor(this.LimitTime/3/intervalOne);
              if (one < 18) {
                one = 18;
                intervalOne = Math.floor(this.LimitTime/3/18);
              };
              console.log(intervalOne);
              for (let i = 0; i < intervalOne; i++) {
                let lisOne = 0;
                if (i == 0) {
                  lisOne = Math.floor(Math.random() * one)+10;
                } else {
                  lisOne = Math.floor(Math.random() * one)+(one*i)+10;
                }
                cameraRandomCapTime.push(lisOne); // 摄像头随机抓拍间隔时间 秒级
              };

              var intervalTwo = this.photoCount - intervalOne-1;
              var twoDate = this.LimitTime/3*2;
              var two = Math.floor(twoDate/intervalTwo);
              if (two < 18) {
                two = 18;
                intervalTwo = Math.floor(this.LimitTime/3*2/18);
              }
              for (let i = 0; i < intervalTwo; i++) {
                let lisTwo = 0
                if (i == 0) {
                  lisTwo = Math.floor(Math.random() * two)+Math.floor(this.LimitTime/3);
                } else {
                  lisTwo = Math.floor(Math.random() * two)+(two*i)+Math.floor(this.LimitTime/3);
                }
                cameraRandomCapTime.push(lisTwo); // 摄像头随机抓拍间隔时间 秒级
              };
              console.log('抓怕的时间', cameraRandomCapTime)
            };
            this.captureNumList = cameraRandomCapTime.sort((a,b)=>a-b);//升序;
            let _this = this;
            this.cameraRandomCapTimer = setInterval(function() {
              _this.currentExamTime++;
              if (cameraRandomCapTime.includes(_this.currentExamTime)) {
                console.log('随机拍照');
                _this.randomCameraFlag = true;
                _this.snapRandom();
              }
            }, 1000);
            this.getQueType();
            this.questionData = res;
            setTimeout(() => {
                this.questionShow = true;
            }, 1000);
            if (res.isUseCamera) {
              this.openCamera();
            }
          } else {
            this.$message.success(res.msg);
            this.$router.push({
              name: 'current'
            });
          }
        });
    },
    // 随机抓拍
    snapRandom() {
      var video = (this.mediaStreamTrack = document.getElementById('video'));
      var canvas2 = document.getElementById('canvas2');
      //绘制canvas图形
      canvas2.getContext('2d').drawImage(video, 0, 0, 320, 240);
      //执行上传
      let completeUrl = canvas2.toDataURL('image/png');
      let urlArr = completeUrl.split(',');
      let base64 = urlArr[1];
      let imgType = urlArr[0].replace('data:image/', '').replace(';base64', '');
      let file_system_url = localStorage.getItem('file_system_url');
      let postUrl = `${file_system_url}&extension=${imgType}&encode=base64`;
      this.$http.post(postUrl, base64).then((data) => {
        if (data) {
          this.randomSaveCameraPage(data.url);
        }
      });
    },
    setAllQuestionAnswer(list) {
      this.allAnswerList = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].QuestionType == 8 || list[i].QuestionType == 9 || list[i].QuestionType == 11 || list[i].QuestionType == 12 || list[i].QuestionType == 13) {
          let lis = {
            questionId: list[i].QuestionId, //题目Id
            questionJson: list[i].StuAnswer, //题目答案
            subQuesList: []
          };
          for (let key = 0; key < list[i].SubQuesList.length; key++) {
            let childLis = {
              questionId: list[i].SubQuesList[key].QuestionId, //题目Id
              questionJson: list[i].SubQuesList[key].SubStuAnswer //题目答案
            };
            lis.subQuesList.push(childLis);
          }
          this.allAnswerList.push(lis);
        } else {
          let lis = {
            questionId: list[i].QuestionId, //题目Id
            questionJson: list[i].StuAnswer, //题目答案
            subQuesList: []
          };
          this.allAnswerList.push(lis);
        }
      }
    },
    // 禁止一些页面作弊功能
    setIsProhibitCopy() {
      if (this.IsProhibitCopy) {
        // 禁止右键菜单
        document.oncontextmenu = function() {
          return false;
        };
        // 禁止文字选择
        document.onselectstart = function() {
          return false;
        };
        // 禁止复制
        document.oncopy = function() {
          return false;
        };
        // 禁止剪切
        document.oncut = function() {
          return false;
        };
        // 禁止粘贴
        document.onpaste = function() {
          return false;
        };
        document.onkeydown = function(e) {
          e = e || event;
          var nums = [116, 123]; //f5:116  f12:123
          for (var i in nums) {
            if (e.keyCode == nums[i]) {
              return false;
            }
          }
        };
      }
    },
    getQueType() {
      // 题目类型 1.单选题(客观),2.多选题(客观),3.判断(客观),5.填空题(主观),6.问答题(主观),7.匹配题(客观),8.阅读理解(客观),9.完形填空(客观),10.文件作答题(主观),11.视听题(客观)
      for (let i = 0; i < this.list.length; i++) {
        var lis = {
          num: i + 1,
          Answer: false,
          QuestionId: this.list[i].QuestionId
        };
        if (this.list[i].QuestionType == 5) {
            let isAnswer = true;
            var StuFillAnswer = '';
            if (this.list[i].StuAnswer) {
              StuFillAnswer = JSON.parse(this.list[i].StuAnswer);
            }
            if (StuFillAnswer) {
                for (let key = 0; key < StuFillAnswer.length; key++) {
                    if (StuFillAnswer[key].Content == '') {
                        isAnswer = false
                    }
                }
            } else {
                isAnswer = false
            }
          lis.Answer = isAnswer;
        } else if (
          this.list[i].QuestionType == 8 ||
          this.list[i].QuestionType == 9 ||
          this.list[i].QuestionType == 11 ||
          this.list[i].QuestionType == 12 ||
          this.list[i].QuestionType == 13
        ) {
          let isAnswer = true;
          for (let key = 0; key < this.list[i].SubQuesList.length; key++) {
            if (this.list[i].SubQuesList[key].StuDo.Answer == '' || this.list[i].SubQuesList[key].StuDo.Answer === null) {
              isAnswer = false;
            }
          }
          lis.Answer = isAnswer;
        } else if(this.list[i].QuestionType == 6) {
          lis.Answer = Boolean(this.list[i].StuAnswer);
          if (this.list[i].fileList != null && this.list[i].fileList.length > 0) {
            lis.Answer = true;
          }
        } else {
          lis.Answer = Boolean(this.list[i].StuAnswer);
        }
        this.answerSheetList.push(lis);
      }
    },
    //获取浏览器类型
    getBrowser() {
      var ua = navigator.userAgent.toLocaleLowerCase();
      var Browser = null;
      if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
        Browser = 'IE';
        browserVersion = ua.match(/msie ([\d.]+)/) != null ? ua.match(/msie ([\d.]+)/)[1] : ua.match(/rv:([\d.]+)/)[1];
        return 'IE';
      } else if (ua.match(/firefox/) != null) {
        Browser = '火狐';
        return 'FF';
      } else if (ua.match(/ubrowser/) != null) {
        Browser = 'UC';
        return 'UC';
      } else if (ua.match(/opera/) != null) {
        Browser = '欧朋';
        return 'OP';
      } else if (ua.match(/bidubrowser/) != null) {
        Browser = '百度';
        return 'baidu';
      } else if (ua.match(/metasr/) != null) {
        Browser = '搜狗';
        return 'SG';
      } else if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        Browser = 'QQ';
        return 'QQ';
      } else if (ua.match(/maxthon/) != null) {
        Browser = '遨游';
        return 'AY';
      } else if (ua.match(/chrome/) != null) {
        var is360 = this.mime('type', 'application/vnd.chromium.remoting-viewer');
        if (is360) {
          Browser = '360';
          return '360';
        } else {
          return 'Chrome';
        }
      } else if (ua.match(/safari/) != null) {
        Browser = 'Safari';
        return 'Safari';
      }
    },
    mime(option, value) {
      var mimeTypes = navigator.mimeTypes;
      for (var mt in mimeTypes) {
        if (mimeTypes[mt][option] == value) {
          return true;
        }
      }
      return false;
    },
    // 判断各种浏览器，找到正确的方法 全屏
    getEnabled() {
      if (document.documentElement.RequestFullScreen) {
        document.documentElement.RequestFullScreen();
      }
      //兼容火狐
      if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
      }
      //兼容谷歌等可以webkitRequestFullScreen也可以webkitRequestFullscreen
      if (document.documentElement.webkitRequestFullScreen) {
        document.documentElement.webkitRequestFullScreen();
      }
      //兼容IE,只能写msRequestFullscreen
      if (document.documentElement.msRequestFullscreen) {
        document.documentElement.msRequestFullscreen();
      }
    },
    // 保存切屏
    saveCutPage() {
      var browser = this.getBrowser();
      this.$http
        .post('/api/study/workexam/saveCutPage', {
          workExamStuId: this.workExamStuId, //学生作答Id
          workExamId: this.Id, //考试Id
          browser: browser //浏览器类型
        })
        .then((res) => {
          if (res.code > 0) {
            this.nowChangeCount = res.stuCatCount;
            if (this.chageCount != -2) {
              this.otherCount = res.otherCount;
              if (this.nowChangeCount >= this.chageCount) {
                this.$message.loading({ content: '切屏次数已达到最大次数！试卷自动提交中' });
                this.randomCameraFlag = true;
                this.loading = true
                this.snapst();
                setTimeout(() => {
                  this.onlineExamSave();
                }, 2000);
              }
            }
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    getBlur() {
      if (this.chageCount != -1) {
        this.visible = true;
      }
    },
    // 学生做题
    getStuAnswer(e,index,num) {
        var questionJson = {};
        questionJson = e;
        for (let i = 0; i < this.answerSheetList.length; i++) {
            if (this.answerSheetList[i].QuestionId == e.QuestionId) {
                if (e.QuestionType == 1 || e.QuestionType == 2 || e.QuestionType == 3 || e.QuestionType == 6 || e.QuestionType == 7) {
                    if (e.StuAnswer == '') {
                        this.answerSheetList[i].Answer = false;
                    } else {
                        this.answerSheetList[i].Answer = true;
                    }
                } else if (e.QuestionType == 4 || e.QuestionType == 5) {
                    let isAnswer = true;
                    for (let key = 0; key < e.StuFillAnswer.length; key++) {
                        if (e.StuFillAnswer[key].Content == '') {
                            isAnswer = false
                        }
                    }
                    this.answerSheetList[i].Answer = isAnswer;
                } else if (e.QuestionType == 8 || e.QuestionType == 9 || e.QuestionType == 11 || e.QuestionType == 12 || e.QuestionType == 13) {
                    let isAnswer = true;
                    for (let key = 0; key < e.SubQuesList.length; key++) {
                        if (e.SubQuesList[key].SubQuestionType == 1 || e.SubQuesList[key].SubQuestionType == 2 || e.SubQuesList[key].SubQuestionType == 3 || e.SubQuesList[key].SubQuestionType == 6) {
                            if (e.SubQuesList[key].StuDo.Answer == '' || e.SubQuesList[key].StuDo.Answer === null) {
                                isAnswer = false;
                            }
                        }
                    }
                    this.answerSheetList[i].Answer = isAnswer;
                }
            }
        }
        this.setAnswerJson(e,index,num);
    },
    // 单题提交数据转换
    setAnswerJson(e,index,num) {
      var questionId = '';
      var answer = '';
      if (e.QuestionType == 1 || e.QuestionType == 2 || e.QuestionType == 3 || e.QuestionType == 6 || e.QuestionType == 7) {
        questionId = e.QuestionId;
        answer = e.StuAnswer;
      } else if (e.QuestionType == 4 || e.QuestionType == 5) {
        questionId = e.QuestionId;
        answer = JSON.stringify(e.StuFillAnswer);
      } else if (e.QuestionType == 8 || e.QuestionType == 9 || e.QuestionType == 11 || e.QuestionType == 12 || e.QuestionType == 13) {
        questionId = e.SubQuesList[num].QuestionId;
        answer = e.SubQuesList[num].StuDo.Answer;
      } else {
        console.log('暂无此题型')
      }
      this.onlineExamAnswer(questionId,answer,index,num);
    },
    // 单题提交
    onlineExamAnswer(questionId, questionJson, index, childnum) {
      var showAnswer = false;
      var data = {};
      setTimeout(() => {
        if (showAnswer == false) {
          this.$message.error('网络错误');
          data = {
            questionId: questionId,
            answer: '',
            num: index,
            childnum: childnum
          }
          if (childnum || childnum == 0) {
            data.answer = this.allAnswerList[index].subQuesList[childnum].questionJson;
          } else {
            data.answer = this.allAnswerList[index].questionJson;
          }
          this.setAnswerSheetList(index,childnum);
          this.$refs.testPaper.setExamAnswer(data);
          // this.$router.push({
          //   name: 'login'
          // });
        }
      }, 6000);
      this.$http
        .post('/api/study/workexam/onlineExamAnswer', {
          examId: this.Id, //考试Id
          workExamStuId: this.workExamStuId, //学生作答Id
          questionId: questionId, //题目Id
          questionJson: questionJson //单题json字符串（获取试卷时单题什么结构，就返回加上答案的json，）
        })
        .then((res) => {
          showAnswer = true;
          if (res.code < 0) {
            this.$message.loading({ content: res.msg });
            this.exitFullscreen();
            this.$router.push({
              name: 'current'
            });
          } else {
            this.showDelayedTime = res.delayedTime;
            data = {
              questionId: questionId,
              answer: res.questionJson,
              num: index,
              childnum: childnum
            }
            if (childnum || childnum == 0) {
              this.allAnswerList[index].subQuesList[childnum].questionJson = res.questionJson;
            } else {
              this.allAnswerList[index].questionJson = res.questionJson;
            }

            if(res.messageRemind != null && res.messageRemind != ""){
              this.$warning({
                title: '监考教师提醒',
                content: res.messageRemind,
                centered: true,
                okText: '确定',
                onOk: () => {this.$http.post('/api/study/WorkExam/ExamMessageRead', 
                {
                  examId: this.Id,
                  paperType: this.paperType
                }).then((res) => {
                  if (res.code > 0) {
                    this.$message.success(res.msg);
                  } else {
                    this.$message.error(res.msg);
                  }
                });
            },
              onCancel() {}
            });

            }             
            this.$refs.testPaper.setExamAnswer(data);
          }
        });
    },
    handleOk() {
      this.visible = false;
      this.getEnabled();
    },
    // 提交失败后执行的
    setAnswerSheetList(index,childnum) {
      if (childnum || childnum == 0) {
            if (this.allAnswerList[index].subQuesList[childnum].questionJson == '' || this.allAnswerList[index].subQuesList[childnum].questionJson == null) {
              this.answerSheetList[index].Answer = false
            }
          } else {
            if (this.allAnswerList[index].questionJson == '' || this.allAnswerList[index].questionJson == null) {
              this.answerSheetList[index].Answer = false
            }
          }
    },
    // 作答时间记录
    setUseTime() {
      this.useTime = localStorage.getItem('useTime' + this.workExamStuId);
      this.useTimeInterval = setInterval(() => {
        this.useTime++;
        this.LimitTime--;
        if (this.needSeconds > 0) {
          this.needSeconds--;
          if (this.needSeconds > 0) {
            this.tiType = 'result';
          } else {
            this.tiType = 'answer';
            this.loading = true;
            this.quesTimeShow = false
            setTimeout(() => {
              this.quesTimeShow= true;
              window.scrollTo(0, 0);
              window.pageYOffset = 0;
              document.documentElement.scrollTop = 0
              document.body.scrollTop = 0;
              this.loading = false
            }, 500);
          }
        }
        if (this.LimitTime <= 0) {
          this.getDelayedTime();
        }
      }, 1000);
    },
    getDelayedTime() {
      this.$http
        .post('/api/study/workexam/getDelayedTime', {
          examId: this.Id //考试Id
        })
        .then((res) => {
          if (res.delayedTime > 0) {
            this.LimitTime = res.delayedTime;
          } else {
            clearInterval(this.useTimeInterval);
            this.$message.loading({ content: '考试时间结束！试卷自动提交中' });
            this.randomCameraFlag = true;
            this.loading = true
            var dom = document.activeElement;
            dom.blur();
            this.snapst();
            setTimeout(() => {
              this.onlineExamSave();
            }, 3000);
          }
        });
    },
    // 提交试卷
    showConfirm() {
      var num = 0;
      for (let i = 0; i < this.answerSheetList.length; i++) {
        if (this.answerSheetList[i].Answer == false) {
          num++;
        }
      }
      var title = '是否确认提交试卷?';
      if (num > 0) {
        title = '还有' + num + '道题未做，是否确认提交试卷?';
      }
      var that = this;
      this.$confirm({
        title: title,
        content: (h) => <div style="color:red;">试卷提交后无法更改</div>,
        cancelText: '取消',
        okText: '确定',
        onOk() {
          that.loading = true;
            that.randomCameraFlag = true;
            that.snapst();
          setTimeout(() => {
            that.onlineExamSave();
          }, 2000);
        },
        onCancel() {
          that.$message.warn('试卷已取消提交');
        },
        class: 'test'
      });
    },
    onlineExamSave() {
      if(this.saving){  //提交试卷中或已经提交成功
        return
      }
      var browser = this.getBrowser();
      var showAnswer = false;
      this.$destroyAll()
      this.saving = true
      setTimeout(() => {
        if (showAnswer == false) {
          this.$message.error('网络错误');
        }
      }, 6000);
      this.$http
        .post('/api/study/workexam/onlineExamSave', {
          examId: this.Id, //考试Id
          uniqueId: this.uniqueId, //试卷Id
          useTime: this.useTime, //作答时长
          stuAnswerJson: JSON.stringify(this.allAnswerList),
          browser: browser, //浏览器类型
          sourceType: 1
        })
        .then((res) => {
          showAnswer = true;
          this.loading = false;
          if (res.code > 0) {
            this.$message.success(res.msg);
            this.exitFullscreen();
            localStorage.removeItem('useTime' + this.workExamStuId);
            this.$router.push({
              name: 'login'
            });
          } else {
            this.saving = false
            this.$message.error(res.msg);
            if (res.code != -2) {
              this.exitFullscreen();
              localStorage.removeItem('useTime' + this.workExamStuId);
              this.$router.push({
                name: 'login'
              });
            }
          }
        });
    },
    // 退出全屏
    exitFullscreen() {
      if (document.exitFullScreen) {
        document.exitFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (element.msExitFullscreen) {
        document.msExitFullscreen();
      }
    },
    handleScroll() {
      this.scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop ||
        document.scrollingElement.scrollTop ||
        0;
      if (this.scrollTop - 20 > this.tabOffsetTop) {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        document.getElementById('home-tab').style.top = (scrollTop-130) + 'px';
      }
    }
  }
};
</script>
